package org.looop.chuck.parser.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.looop.chuck.domain.AppInfo;
import org.looop.chuck.persistence.PersistenceManager;
import org.looop.chuck.task.URLTaskManager;
import org.w3c.dom.Element;

public class ApkDetailHTMLParser extends AppInfoListHTMLParser {
	private String url;
	private static Pattern urlPattern = Pattern.compile("http://apk\\.hiapk\\.com/html/\\d{4}/\\d{2}/\\d+\\.html");
	public ApkDetailHTMLParser(PersistenceManager persistenceManager,
			URLTaskManager urlTaskManager, String url) {
		super(persistenceManager, urlTaskManager);
		this.url = url;
	}

	@Override
	protected List<AppInfo> extraAppInfoList(Element rawDoc) {
		List<AppInfo> appInfoList = new ArrayList<AppInfo>();
		String appName = getAppName(rawDoc);
		String categoryName = getCategoryName(rawDoc);
		if(StringUtils.isNotBlank(appName) && StringUtils.isNotBlank(categoryName)){
			AppInfo appInfo = new AppInfo();
			appInfo.setName(appName);
			appInfo.setCategory(categoryName);
			appInfo.setUrl(url);
			appInfoList.add(appInfo);
		}
		return appInfoList;
	}

	private String getCategoryName(Element rawDoc) {
		List<Element> list = getElementByTagNameAndAttribute(rawDoc, "span", "id", "ctl00_AndroidMaster_Content_Soft_CurrentCategory");
		if(list.size() > 0){
			Element element = list.get(0);
			return getInnerText(element);
		}
		return null;
	}

	private String getAppName(Element rawDoc) {
		List<Element> list = getElementByTagNameAndAttribute(rawDoc, "label", "id", "ctl00_AndroidMaster_Content_Apk_SoftName");
		if(list.size() > 0){
			Element element = list.get(0);
			return getInnerText(element);
		}
		return null;
	}

	@Override
	protected List<String> gernerateNewTask(Element rawDoc) {
		return Collections.emptyList();
	}
	
	public static boolean match(String url){
		Matcher matcher = urlPattern.matcher(url);
		return matcher.find();
	}
}
